#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :phone_number_location.py
# @Time      :2025/8/2 13:57
# @Author    :Ethon

# 手机号段库
import os
import json
from pathlib import Path


class PhoneNumberLocator:
    def __init__(self, data_dir='src'):
        self.data_dir = Path(data_dir)
        self.prefix_map = {}  # 存储所有手机号段与归属地的映射

        # 加载所有JSON文件
        self._load_data()

    def _load_data(self):
        """加载指定目录下的所有JSON文件"""
        for json_file in self.data_dir.glob('*.json'):
            try:
                with open(json_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.prefix_map.update(data)
            except Exception as e:
                print(f"Error loading {json_file}: {str(e)}")

    def find_location(self, phone_number):
        """查询手机号归属地信息"""
        # 验证手机号格式
        if not (phone_number.isdigit() and len(phone_number) == 11):
            return {"error": "Invalid phone number format"}

        # 提取前7位作为号段
        prefix = phone_number[:7]

        # 查找归属地信息
        if prefix in self.prefix_map:
            return self.prefix_map[prefix]
        else:
            return {"error": "Phone prefix not found"}


# 使用示例
if __name__ == "__main__":
    locator = PhoneNumberLocator()  # 默认从src目录加载数据

    # 测试手机号
    test_numbers = [
        "13400001234",  # 示例中的号段
        "13912345678",  # 可能存在的其他号段
        "199171",  # 无效号码
        "abcdefghijk"  # 非数字号码
    ]

    # 查询并打印结果
    for number in test_numbers:
        result = locator.find_location(number)
        print(f"手机号: {number}")
        print("归属地信息:", result)
        print("-" * 40)